<template>
  <div class="home">
    <div class="top">
      <a-config-provider :autoInsertSpaceInButton="false">
        <!-- <a-button
          type="primary"
          size="large"
          :autoInsertSpaceInButton="false"
          style="border-radius:0px;width:96px;font-size: 17px;"
          @click="showModal"
        >新增</a-button>-->
        <a-button type="primary" icon="plus" @click="showModal">新增</a-button>
      </a-config-provider>
    </div>
    <div class="center">
      <div v-for="(item,index) in data" :key="index">
        <div class="title flexBetween">
          <div>{{item.place}}</div>
          <div>
            <a-button :autoInsertSpaceInButton="false" type="link" @click="onEdit(item)">
              <!-- style="border-radius:4px;width:80px;height:35px;font-size: 15px;color:#fff;background:#08C179;border-color:#08C179" -->
              <a-icon type="edit" class="a-icon" />编辑
            </a-button>

            <a-popconfirm
              title="是否确认删除"
              ok-text="确认"
              cancel-text="取消"
              @confirm="confirm(item)"
              @cancel="cancel"
            >
              <a-button type="link" style="color:#f00">
                <!-- style="border-radius:4px;width:80px;height:35px;font-size: 15px;color:#fff;margin-left:30px" -->
                <a-icon type="delete" class="a-icon" />删除
              </a-button>
            </a-popconfirm>
            <!-- <div @click="itemData(item)">
              <a-dropdown-button>
                <a-menu slot="overlay" @click="handleMenu">
                  <a-menu-item key="1">
                    <a-icon type="edit" />编辑
                  </a-menu-item>
                  <a-menu-item key="2">
                    <a-icon type="delete"/>删除
                  </a-menu-item>
                </a-menu>
              </a-dropdown-button>
            </div>-->
          </div>
        </div>
        <div class="content flexStart">
          <div>设立时间：{{item.releaseDate}}</div>
          <div>负责人：{{item.manager}}</div>
          <div>最近一次更新时间：{{item.updateTime}}</div>
        </div>
        <!-- <div class="imgDiv flexStart" v-if="item.fileList.length!=0" style="width:100%"> -->
        <!-- @click="imgshow(data.fileUrl)" -->
        <!-- <div
            class="img"
            :style="styleVar"
            v-for="(data,index) in item.fileList"
            :key="index"
            v-viewer
          >
            <img :src="data.fileUrl" width="100%" height="100%" alt />
        </div>-->

        <viewer
          :images="item.fileList"
          class="imgDiv flexStart"
          v-if="item.fileList.length!=0"
          style="width:100%"
        >
          <div class="img" :style="styleVar" v-for="(src,index) in item.fileList" :key="index">
            <img :src="src.fileUrl" width="100%" height="100%" />
          </div>
        </viewer>
        <!-- </div> -->
      </div>
    </div>
    <!-- <mirror :width="width" :picList="picList" /> -->

    <!-- <zoom :previewImg="min" :zoomImg="max"></zoom> -->
    <!-- 对话框 -->
    <a-modal
      v-model="visible"
      :title="modalTitle"
      @ok="handleOk"
      :maskClosable="false"
      cancelText="取消"
      okText="确认"
    >
      <a-form-model ref="ruleForm" :model="form" :rules="rules" v-if="visible">
        <!-- :label-col="labelCol"
        :wrapper-col="wrapperCol"-->
        <a-form-model-item ref="place" label="地点" prop="place">
          <a-input
            v-model="form.place"
            :maxLength="30"
            @blur="
          () => {
            $refs.place.onFieldBlur();
          }
        "
          />
        </a-form-model-item>

        <a-form-model-item ref="releaseDate" label="设立时间" prop="releaseDate">
          <a-date-picker
            v-model="form.releaseDate"
            type="date"
            placeholder="请选择日期"
            style="width: 100%;"
          />
        </a-form-model-item>

        <a-form-model-item ref="manager" label="负责人" prop="manager">
          <a-input
            v-model="form.manager"
            :maxLength="30"
            @blur="
          () => {
            $refs.manager.onFieldBlur();
          }
        "
          />
        </a-form-model-item>

        <a-form-model-item label="备注">
          <a-input v-model="form.remark" type="textarea" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-model-item>

        <a-form-model-item label="维权信息告示牌" prop="formUpload">
          <div class="clearfix">
            <a-upload
              name="file"
              accept=".bmp, .gif, .png, .jpeg, .jpg"
              list-type="picture-card"
              :file-list="fileList"
              @preview="handlePreview"
              :remove="handleRemove"
              :before-upload="beforeUpload"
            >
              <div>
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
            <a-modal
              :visible="previewVisible"
              :footer="null"
              @cancel="handleCancel"
              class="pdfModal"
            >
              <img
                v-if="previewVisible"
                alt="example"
                width="1000"
                height="700"
                :src="previewImage"
              />
            </a-modal>
          </div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 照片弹出框 -->
    <div>
      <a-modal
        v-model="visible2"
        title
        @ok="handleOk2"
        :footer="null"
        :maskClosable="false"
        width="1080px"
        :centered="true"
        class="pdfModal"
        :bodyStyle="{textAlign:'center'}"
        v-if="visible2"
        key="modalpdf"
      >
        <img
          v-if="visible2"
          width="1000"
          height="700"
          :src="imgSrc"
          alt
          :style="{transform:'scale('+multiples+')'}"
        />
      </a-modal>
    </div>
    <!-- <viewer :images="picList">
      <img v-for="(src,index) in picList" :src="src" :key="index" title=" " />
    </viewer>-->
  </div>
</template>

<script>
import moment from 'moment'
import { message } from 'ant-design-vue'

import {
  rightProtectionBoardAdd,
  rightProtectionBoardQuery,
  rightProtectionBoardGet,
  rightProtectionBoardUpdate,
  rightProtectionBoardDelete
} from '@/api/rightProtectionBoard.js'
import { uploadOSS } from '@/utils/oss.js'
import { mapGetters } from 'vuex'

export default {
  data() {
    let formUpload = (rule, value, callback) => {
      // console.log(this.fileList.length);

      if (this.imgupload == false) {
        callback(new Error('请上传图片'))
      } else {
        this.$refs.ruleForm.validateField('formUpload')
        callback()
      }
    }
    return {
      multiples: 1,
      modalTitle: '新增维权信息告示牌',
      visible: false,
      visible2: false,
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 12
      },
      form: {
        id: '',
        packageId: '',
        fileInfoList: [],
        manager: '',
        place: '',
        releaseDate: moment(new Date()),
        remark: ''
      },
      width: 500,
      // picList: [{
      //   url:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20171119%2F0779770886a6433e9a44bf1bf8ad442a.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625015981&t=9046f94ab202a56aaa0d4969e1b8588c',
      //   name:'img1'
      //   },
      //   {
      //   url:'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20180720%2F73590a471560463e8a270da31374b67f.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625015981&t=b942bdae23c3ebb2589a75cd39f6422f',
      //   name:'img2'
      //   }
      //   ],
      picList: [
        'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20171119%2F0779770886a6433e9a44bf1bf8ad442a.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625015981&t=9046f94ab202a56aaa0d4969e1b8588c',

        'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20180720%2F73590a471560463e8a270da31374b67f.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625015981&t=b942bdae23c3ebb2589a75cd39f6422f'
      ],
      previewVisible: false,
      min:
        'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20171119%2F0779770886a6433e9a44bf1bf8ad442a.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625015981&t=9046f94ab202a56aaa0d4969e1b8588c',
      max:
        'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20171119%2F0779770886a6433e9a44bf1bf8ad442a.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625015981&t=9046f94ab202a56aaa0d4969e1b8588c',
      previewImage: '',
      fileList: [],
      imgupload: false,
      flag: false,
      data: [],
      rules: {
        place: [
          {
            required: true,
            message: '请输入地点',
            trigger: 'change'
          }
        ],
        releaseDate: [
          {
            required: true,
            message: '请输入设立时间',
            trigger: 'change'
          }
        ],
        manager: [
          {
            required: true,
            message: '请输入负责人',
            trigger: 'change'
          }
        ],
        formUpload: [
          {
            required: true,
            validator: formUpload,
            trigger: 'change'
          }
        ]
      },
      imgSrc: '',
      screenWidth: document.body.clientWidth,
      itemValue: {}
    }
  },
  
  mounted() {
    this.getTable()
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
  },
  computed: {
    styleVar() {
      return {
        height: 0.15 * this.screenWidth + 'px'
      }
    },
    ...mapGetters(['userInfo'])
  },
  watch: {
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        let that = this
        setTimeout(function() {
          // 打印screenWidth变化的值
          // console.log(that.screenWidth)
          that.timer = false
        }, 400)
      }
    }
  },
  methods: {
    moment,
    itemData(val) {
      console.log(val)
      this.itemValue = val
    },
    // 放大
    toBIgChange() {
      if (this.multiples >= 2) {
        return
      }
      this.multiples += 0.25
    },
    // 缩小
    toSmallChange() {
      if (this.multiples <= 1) {
        return
      }
      this.multiples -= 0.25
    },
    getTable() {
      let data1 = {}
      data1.likeName = ''
      data1.page = 0
      data1.size = 0
      data1.orgId = this.userInfo.orgId
      // data1.projectId = this.userInfo.projectId
      let _this = this

      rightProtectionBoardQuery(data1).then((res) => {
        let tabdata = res.data.data
        _this.data = []
        tabdata.forEach((item, index) => {
          item.key = item.id
          item.releaseDate = moment(item.releaseDate).format('YYYY-MM-DD')
          item.updateTime = moment(item.updateTime).format('YYYY-MM-DD')
          item['description'] = {}
          item['description']['data'] = item.fileList
          item['description']['people'] = item.updateId
          item['description']['updateTime'] = item.updateTime
        })
        _this.data = tabdata
        this.total = res.data.total
        // console.log(tabdata);
      })
      // this.data=[{fileList:[{a:1}]}]
    },
    onEdit(item) {
      this.modalTitle = '编辑维权信息告示牌'
      this.form.packageId = ''
      this.form.fileInfoList = []
      this.fileList = []
      this.form.place = ''
      this.form.releaseDate = moment(new Date())
      this.form.manager = ''
      this.form.remark = ''
      this.form.place = item.place
      this.form.releaseDate = moment(new Date(item.releaseDate))
      this.form.remark = item.remark
      this.form.id = item.id
      this.form.manager = item.manager
      this.form.packageId = item.packageId
      item.fileList.forEach((itemData, index) => {
        let fileObj = {}
        fileObj['uid'] = index
        fileObj['status'] = 'done'
        fileObj['url'] = itemData.fileUrl
        fileObj['name'] = itemData.fileName
        this.form.fileInfoList.push(fileObj)
        this.fileList.push(fileObj)
      })
      if (this.fileList.length != 0) this.imgupload = true
      this.visible = true
    },
    handleMenu(e) {
      switch (parseInt(e.key)) {
        case 1:
          // console.log(111);

          this.onEdit(this.itemValue)
          break
        case 2:
          // console.log(222);
          this.onDelete(this.itemValue)
          break
      }
    },
    showModal() {
      this.form.packageId = ''
      this.form.fileInfoList = []
      this.fileList = []
      this.form.place = ''
      this.form.releaseDate = moment(new Date())
      this.form.manager = ''
      this.form.remark = ''
      this.modalTitle = '新增维权信息告示牌'
      this.flag = true
      this.imgupload = false
      this.visible = true
    },
    handleOk(e) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = {}
          data['fileInfoList'] = []
          this.form.fileInfoList.forEach((item, index) => {
            let obj = { fileName: '', fileUrl: '' }
            obj.fileName = item.name
            obj.fileUrl = item.url
            data['fileInfoList'].push(obj)
          })
          data.place = this.form.place
          data.manager = this.form.manager
          data.releaseDate = this.form.releaseDate
          data.id = this.form.id
          data.packageId = this.form.packageId
          data.remark = this.form.remark
          if (this.modalTitle != '编辑维权信息告示牌') {
            rightProtectionBoardAdd(data).then((res) => {
              // console.log(res)
              this.$message.destroy()
              this.$message.success('新增成功')
              this.visible = false
              this.getTable()
            })
          } else {
            rightProtectionBoardUpdate(data)
              .then((res) => {
                // console.log(res)
                this.$message.destroy()
                this.$message.success('编辑成功')
                this.visible = false
                this.getTable()
              })
              .catch((err) => {})
          }
        } else {
          // console.log('error submit!!');
          return false
        }
      })
    },
    handleOk2() {
      this.visible2 = false
    },
    imgshow(img) {
      this.imgSrc = img
      this.visible2 = true
    },
    onDelete(text) {
      let data = {}
      data.id = text.id
      rightProtectionBoardDelete(data).then((res) => {
        message.destroy()
        this.$message.success('删除成功')
        this.getTable()
      })
    },
    confirm(item) {
      // console.log(e);
      this.onDelete(item)
    },
    cancel(e) {
      // console.log(e);
      this.$message.error('取消删除')
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      // console.log(file)

      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleRemove(file) {
      console.log(file.uid)
      this.form.fileInfoList.forEach((item, index) => {
        if (file.uid == item.uid) {
          this.form.fileInfoList.splice(index, 1)
          this.fileList.splice(index, 1)
        }
      })
      if (this.form.fileInfoList.length != 0) {
        this.imgupload = true
      } else {
        // console.log(111);

        this.imgupload = false
      }
      // this.form.fileInfoList
    },

    beforeUpload(file) {
      // console.log(file)
      if (this.configFun.image(file)) {
        const reader = new FileReader()
        reader.readAsDataURL(file) // 读取图片文件
        if (this.modalTitle != '编辑维权信息告示牌' && this.flag == true) {
          this.form.packageId = file.uid
          this.flag = false
        }
        reader.onload = (data) => {
          // console.log(data, file.name, file.uid, this.form.packageId)
          this.uploadFile(data.target.result, file.name, file.uid, this.form.packageId)
        }
        this.imgupload = true
      } else {
        // this.defaultFileList = []
        // this.flagUpload=true
        this.$message.destroy()
        this.$message.error('你上传的不是图片')
        return false
      }
      //
      return false
    },
    uploadFile(base64Data, fileName, fileUid, packageId) {
      // console.log(base64Data)

      let blob = this.dataURLtoBlob(base64Data)
      let dir = 'lw/' + 'RB' + packageId + '/'
      uploadOSS(blob, fileName, dir).then((fileUrl) => {
        // console.log(fileUrl, fileName)
        let obj = { url: fileUrl, name: fileName, uid: fileUid }
        // console.log( obj.fileUid );
        this.form.fileInfoList.push(obj)
        this.fileList.push(obj)
        this.$message.success(`${file.name} 上传成功`, 1)
      })
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], {
        type: mime
      })
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
      })
    }
  }
}
</script>

<style scoped lang="less">
.home {
  font-size: 20px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #333333;
}

.top {
  // margin-bottom: 10px;
  background: #fff;
  padding: 18px 30px;
}

.center {
  padding: 15px 30px;
  background: #fff;
}

.title {
  font-size: 20px;
  color: #333333;
  height: 50px;
  padding-top: 11px;
  line-height: 31px;
  border-bottom: 1px solid #e4e4e4;
  padding-bottom: 19px;
  margin-bottom: 25px;
}

.content {
  font-weight: 400;
  color: #999999;
  // line-height: 31px;
  font-size: 16px;
  margin-bottom: 30px;
}

.content div {
  margin-right: 60px;
}

.img {
  min-width: 22%;
  max-width: 22%;
  width: 22%;
  // padding-bottom:75%;
  // height: 200px;
  margin-bottom: 30px;
  margin-right: 2%;
}
// .imgDiv .img:first-child {
//   margin-left: 1%;
// }
// .imgDiv .img:last-child {
//   margin-right: 1%;
// }

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.a-icon {
  cursor: pointer;
}

.flexBetween {
  align-items: center;
}
.pdfModal {
  ::v-deep .ant-modal {
    width: 1080px !important;
    // top: 20px;
  }
}
.pdfModal ::v-deep .ant-modal-body {
  padding: 40px;
  text-align: center;
  height: 780px;
}
.flexStart {
  flex-wrap: wrap;
}
::v-deep .ant-modal {
  padding-bottom: 0;
}
::v-deep .viewer-title {
  display: none;
}
</style>
